package com.xiaolin.sports.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xiaolin.sports.common.RspResult;
import com.xiaolin.sports.common.enums.Status;
import com.xiaolin.sports.model.ParentInfo;
import com.xiaolin.sports.model.SmsValidateCode;
import com.xiaolin.sports.service.IParentInfoService;
import com.xiaolin.sports.service.ISmsValidateCodeService;
import com.xiaolin.sports.utils.BeanUtils;
import com.xiaolin.sports.vo.ParentQueryVO;
import com.xiaolin.sports.wechat.model.WechatUserInfo;

@RequestMapping("parent")
@Controller
public class ParentController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(ParentController.class);
	
	@Autowired
	private IParentInfoService parentInfoService;
	@Autowired
	private ISmsValidateCodeService smsValidateCodeService;
	
	@RequestMapping("update")
	@ResponseBody Object upate(ParentQueryVO vo) {
		try {
			WechatUserInfo userInfo = getWechatUserInfo();
			Boolean isBind = false;
			if(vo.getValidCode() != null) {
				SmsValidateCode code = new SmsValidateCode();
				code.setCode(vo.getValidCode());
				code.setMobile(vo.getParentMobile());
				int count = smsValidateCodeService.isValid(code);
				if(count == 0) {
					return new RspResult(Status.SMS_VAILD_FAIL);
				}
				isBind = true; 
			}
			ParentInfo parentInfo = parentInfoService.selectByOpenid(userInfo.getOpenid());
			ParentInfo record = BeanUtils.copyAs(vo, ParentInfo.class);
			record.setId(parentInfo.getId());
			if(isBind) record.setIsBind(1);
			parentInfoService.addAndUpdate(record);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.debug("-----logger error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
}
